package com.bst.web.query;

import com.alibaba.fastjson.JSONObject;
import com.bst.common.annotation.Log;
import com.bst.common.core.domain.AjaxResult;
import com.bst.common.enums.BusinessType;
import com.bst.etl.service.IDwQueryService;
import com.bst.etl.vo.DwQueryVO;
import com.bst.common.vo.HeaderAndBodyVO;
import com.bst.md.domain.MdMedPubfld;
import com.bst.md.service.IMdMedPubfldService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/hos/qry/dw")
public class DwPubQueryController {

    @Autowired
    IDwQueryService dwQueryService;
    @Autowired
    IMdMedPubfldService mdMedPubfldService;

    @Log(title = "DW明细数据查询", businessType = BusinessType.QUERY)
    @PostMapping("/showDwData")
    public String showDwData(@RequestBody DwQueryVO queryVO, ModelMap mmap) {
        AjaxResult result = this.query(queryVO);
        mmap.put("data", JSONObject.toJSONString(result.get(AjaxResult.DATA_TAG)));
        return "chart/template/table";
    }

    @ApiOperation(value="表格显示-实时数据")
    @RequestMapping(value="/query", method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult query(@RequestBody DwQueryVO queryVO) {
        List<Map<String,Object>> dataList = dwQueryService.queryFromDw(queryVO);
        Map<String,String> header = new LinkedHashMap<>();
        if(dataList.size()>0) {
            List<String> idPubfldList = new ArrayList<>();
            for(String key:dataList.get(0).keySet()) {
                idPubfldList.add(key);
            }
            List<MdMedPubfld> pubfldList = mdMedPubfldService.findByIdList(idPubfldList);
            if(pubfldList.size()>0) {
                header = pubfldList.stream().collect(Collectors.toMap(MdMedPubfld::getIdPubfld,MdMedPubfld::getNa));
            }
            Object time;String timeDes;
            for (Map<String, Object> map : dataList) {
                time = map.get("ID_DIM_TIME_OCCUR");
                if(time!=null) {
                    timeDes = time.toString().replaceAll("(.{2})", "$1:");
                    map.put("ID_DIM_TIME_OCCUR",timeDes.substring(0,timeDes.length()-1));
                }
            }
        }
        HeaderAndBodyVO headerAndBodyVO = new HeaderAndBodyVO();
        headerAndBodyVO.setThead(header);
        headerAndBodyVO.setTbody(dataList);
        return AjaxResult.success(headerAndBodyVO);
    }
}
